package cn.bdqn.controller;

import cn.bdqn.entity.User;
import cn.bdqn.enums.JxcEnum;
import cn.bdqn.exception.JxcException;
import cn.bdqn.service.UserService;
import cn.bdqn.utils.ResultVoUtil;
import cn.bdqn.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 郑大仙丶
 * @date 2018-12-28 16:40
 */
@RestController // @ResponseBody + @Controller
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    private final String USER_ATTRIBUTE = "users";

    //vo -> View Object
    @RequestMapping(value = "/doLogin",method = RequestMethod.POST)
    public ResultVo doLogin(HttpSession session,
                            @RequestParam String username,
                            @RequestParam String password){
        //1. 执行登录.
        User user = userService.login(username, password);
        //2. 将用户信息放到session.
        session.setAttribute(USER_ATTRIBUTE,user);
        //3. 响应json数据
        return ResultVoUtil.success();
    }


    /*
    退出登录
    响应数据
        成功
            {
                code : 200,
                message : 成功,
                data : null
            }
        失败
            {
                code : 异常编码,
                message : 错误的信息,
                data : null
            }
     */

    @RequestMapping(value = "/logout",method = RequestMethod.POST)
    public ResultVo logout(HttpSession session){
        //1. 判断用户是否登录.
        Object users = session.getAttribute(USER_ATTRIBUTE);
        if(users == null){
            throw new JxcException(JxcEnum.USER_NOT_LOGIN);
        }
        //2. 清空session
        session.removeAttribute(USER_ATTRIBUTE);
        //3. 响应
        return ResultVoUtil.success();
    }


}
